package com.chixing.fourteen.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chixing.fourteen.pojo.Customer;
import com.chixing.fourteen.pojo.CustomerOrder;
import com.chixing.fourteen.service.CustomerOrderService;
import com.chixing.fourteen.service.MeterService;
import com.chixing.fourteen.service.impl.CustomerOrderServiceImpl;
import com.chixing.fourteen.service.impl.MeterServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Random;

/**
 * @author Y2014188432
 */
@Controller
@RequestMapping("/meter")
public class MeterController {

    @Autowired
    private MeterService meterService = new MeterServiceImpl();

    @Autowired
    private CustomerOrderService customerOrderService = new CustomerOrderServiceImpl();

    @GetMapping("/mypay")
    public String mypay(Model model,int customerOrderId,double price){
        model.addAttribute("customerOrderId",customerOrderId);
        model.addAttribute("price",price);
        return "pay";
    }


    @RequestMapping("/alipay")
    public void alipay(HttpServletResponse httpResponse, Double price, int customerOrderId) throws IOException {
        String productName = "carPrice";
        Random r=new Random();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                "2021000117667098",
                "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC1FuPiMjHVkarqgV7r2P233gtrHRcfhuwdKxQrjbRaiGjSYzyuiSnQ0zB4UygezVwiqGRxZ7ZFxEbHD5BiNAiHOwueEWtg4zVO09djnxcrnu9fAoSQZjIAHTwbVyhN2efaI+SkPfxVqP5Fqqw2a0w8xxWQ1EkIQmC1Fd9VL6hak9O1IMHsCHE96lDoYJ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fgNK5kMV0Bo0Yi40vuziYrfA4oQwuHoq2DvpN0Q3MDZf37jETkFsTK2LJ/uewXhcAE67+a9UQ2NFfHHJjN5t7O5Iq0wMJ5gJGa7y3IEoCYNcFUlOzWZse5OgFEVW+w4t+v6pty/gRkHJwKBgQC+nq7rLu2Q0ccxsnhcjgy/V0HG7TVQY27FFVSHAsI8DVLaoFYbSWk5JC6DkVReHRwmUcE8x8B5vTurdiOBj6gdDN41/axVDLTSQYlhLwgnMmaEJs/4OU/Mg2rZokm1ARcL8fTlfnuH+QCA6tyA7loraP/cEu1rth5R64pXmrY3JA==",
                "json",
                "GBK",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwWlpU76d6FzibCWMG7h71kcegbWvQ0HFMzZdyYiTKkvuFcgiOMhEg+b7RC5+UCMza/If6HrfujO2c7fytOJ1X+4uVUmD67g0fm30ym/eKheUHOWG5mC3XXHk0nXuAYMxHRmfJZT5RK9z+UMVDmOZHwGmXePEmpV+r+2QsZM2IYEPZNxcOM46fppNm/kCRTBGv0I77bGXEKY/cSmuW8qTI4w3CriC1e16gy1Wk9Ndbxi9v8f3O4nczWxVwt7G6UGGd9Kvfhq75f54OBwIHyoE7DBtFgMtnjXExJHhPwIOAoYu+zrwAV5VrPiTrVVNQdesMTLL17Vcrw3I7Rjv21nw1QIDAQAB",
                "RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl("http://192.168.4.217:8080/meter/toPayPage/");
        request.setNotifyUrl("http://192.168.4.217:8080/meter/toPayPage/");

        request.setBizContent("{" +
                "\"out_trade_no\":" + "\""+String.valueOf(customerOrderId) +"\","+
                "\"total_amount\":" + "\""+price +"\","+
                "\"subject\":" + "\""+productName +"\","+
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\","+
                "\"timeout_express\":"+"\"5m\""+
                "}");

        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=utf-8");
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @RequestMapping("/toPayPage")
    public String Notify(HttpServletResponse response, HttpServletRequest request,Model model) throws Exception {
        // 商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "GBK");
        // 付款金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "GBK");
        // 支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "GBK");
        model.addAttribute("total_amount",total_amount);
        model.addAttribute("out_trade_no",out_trade_no);
        model.addAttribute("trade_no",trade_no);
        return "pay";
    }

    @GetMapping("/create")
    public String createMeter(HttpServletRequest request, String customerOrderId, String price,String type){
        HttpSession session = request.getSession();
        Customer customer = (Customer) session.getAttribute("customer");
        int customerId = customer.getCustomerId();
        meterService.createMeter(Integer.parseInt(customerOrderId), customerId, Double.parseDouble(price), type);
        customerOrderService.changeStatus(Integer.parseInt(customerOrderId),4);
        return "homepage";
    }

    @GetMapping("/pay")
    public String jumpPay(HttpServletRequest request, Model model, int customerOrderId){
        HttpSession session = request.getSession();
        Customer customer = (Customer)session.getAttribute("customer");
        int customerId = customer.getCustomerId();
        model.addAttribute("customerId",customerId);
        model.addAttribute("customerOrderId",customerOrderId);
        return "pay";
    }

}
